<?php
namespace org\util;

/**
 * 广告图片上传类
 * 页面样式参考:http://mq.wsq.qq.com/143246866/t/new?sid=ARE5fyoCBxUZT8M64-IrrIUh
 * 如果需要发送其他头部信息，可以参考:http://www.cnblogs.com/meteoric_cry/archive/2011/06/07/2073987.html
 */
class H5Upload {

	var $m;
	var $uid;

	var $attachs;

	var $fileName;
	var $fileType;
	var $fileSize;
	var $fileData;

	var $ifthumb;
	var $thumbsize;
	var $uploadImgNum;

	var $uploadInfo;

	var $error;

	var $oldAttachs = array();

	var $source = ''; //上传文件保存路径+文件名

	var $savePath;
	var $saveFtpPath; //上传FTP保存路径
	var $saveFtpName; //上传FTP保存文件名

	/**
	 * 初始化
	 */
	function __construct() {
/*
		$this->uid = $uid;
		$this->fid = $fid;
		$this->data = $fileData;

		$this->ifthumb	 = $db_ifathumb;
		$this->thumbsize = $db_athumbsize;
*/
		$this->savePath = PUBLIC_PATH.'runtime/h5upload/';
    	//$this->savePath = __DIR__.'/../../../data/h5upload/';
    	if (!is_dir($this->savePath)) {
	    	mkdir($this->savePath);
	    }
		$this->uploadImgNum = 0;

	}

	public function upload() {
		if (!$this->init()) { //初始化
			return false;
		}

		$this->saveFtpName = $this->buildFileName();
		$this->source = $this->savePath.$this->saveFtpName;

		if (!$this->createImage()) { //保存上传文件到临时目录
			return false;
		}
		
		if (!$this->verifyImage()) { //验证图片
			return false;
		}

		//$this->fileuploadurl = $this->saveFtpPath.$this->saveFtpName;
		//echo $this->fileuploadurl;exit;

		//todo 水印

		$this->moveTo(); //将文件从临时目录移动到附件目录

		$this->delOldAttachs();

		return true;
	}

	//验证及初始化
	private function init() {
		//验证文件内容
		if (!$this->fileData) { //这个地方不能加
			return false;
		}

		//验证文件大小
		if ($this->fileSize <= 0) {
			$this->error = '文件大小非法';
			return false;
		}

		//获取文件类型
		$this->fileType = str_replace('image/', '', $this->fileType);

		//获取图片data
		// if ($this->fileType == 'jpeg') {
		// 	$this->fileType = 'jpg';
		// 	$this->fileData = base64_decode(str_replace('data:image/jpeg;base64,', '', $this->fileData));
		// } else {
		// 	$this->fileData = base64_decode(str_replace('data:image/png;base64,', '', $this->fileData));
		// }

		if ($this->fileType == 'jpeg') {
			$this->fileType = 'jpg';
		}

		if (strpos($this->fileData, 'data:image/jpeg') === 0) {
			$this->fileData = base64_decode(str_replace('data:image/jpeg;base64,', '', $this->fileData));
		}

		if (strpos($this->fileData, 'data:image/png') === 0) {
			$this->fileData = base64_decode(str_replace('data:image/png;base64,', '', $this->fileData));
		}

		// $this->fileType = 'jpg';
		// $this->fileData = base64_decode(str_replace('data:image/jpeg;base64,', '', $this->fileData));

		return true;
	}

	//获取文件路径
	private function buildFileName() {
		//if ($this->saveFtpName) {
			$prename = $this->saveFtpName;
		//} else {
			$time = time();
			$prename  = substr(md5($time.randstr(8)), 10, 15);
		//}
		$savename = $prename.'.'.$this->fileType;
		return $savename;
	}

	//保存上传文件到临时目录
	private function createImage() {
		file_put_contents($this->source, $this->fileData);
		if (!file_exists($this->source)) {
			$this->error = '文件生成，可能是目录不可写';
			return false;
		}
		$this->uploadInfo = getimagesize($this->source);

		$this->uploadInfo['name'] = $this->fileName;
		$this->uploadInfo['savename'] = $this->saveFtpName;
		$this->uploadInfo['size'] = ceil(filesize($this->source)/1024); //图片大小
		$this->uploadInfo['ext'] = $this->fileType;

		$this->uploadInfo['attachurl'] = $this->saveFtpPath.$this->saveFtpName;
		
        return true;
	}

	//验证图片类型是否非法
	private function verifyImage() {
		if (!$this->uploadInfo) {
			$this->error = '文件生成失败';
			return false;
		}
		if (strpos($this->uploadInfo['mime'], 'image') !== 0) {
			$this->error = '图片非法';
			return false;
		}
		return true;
	}

	//将文件从临时目录移动到附件目录
	function moveTo() {
        //远程附件
        if (config('FTP_STATUS') == 1) {
            $ftpConfig = config('FTP_CONFIG');
            //print_r($ftpConfig);exit;
            $ftp = new \org\util\FtpCmd();
            $ftp->init($ftpConfig['server'], $ftpConfig['port'], $ftpConfig['username'], $ftpConfig['password'], $ftpConfig['dir']);
            //$ftpFilePath = $this->saveFtpPath.$this->saveFtpName;

// 			echo 'source:'.$this->source;
// 			echo '<br>';
// 			echo 'ftpFilePath:'.$ftpFilePath;
// 			exit;
            if ($ftp->upload($this->source, $this->uploadInfo['attachurl'])) {
                @unlink($this->source);
                return true;
            } else {
                $this->error = 'ftp 上传失败！';
                return false;
            }
        }
	}

	//删除旧的附件
	function delOldAttachs() {
		if (count($this->oldAttachs) > 0) {
			//远程附件
			if (config('FTP_STATUS') == 1) {
				$ftpConfig = config('FTP_CONFIG');
				$ftp = new \org\util\FtpCmd();
				$ftp->init($ftpConfig['server'], $ftpConfig['port'], $ftpConfig['username'], $ftpConfig['password'], $ftpConfig['dir']);

				foreach ($this->oldAttachs as $key => $value) {
					//echo $value;exit;
					$ftp->delete($value);
				}
			}
		}
	}

	function getAttachUrl() {
		return $this->uploadInfo['attachurl'];
	}
	function getUploadInfo() {
		return $this->uploadInfo;
	}

	function getAttachs() {
		return $this->attachs;
	}
	function getAids() {
		return array_keys($this->attachs);
	}
	function getAttachNum() {
		return count($this->attachs);
	}

    /**
     * 返回模型的错误信息
     * @access public
     * @return string
     */
    public function getError(){
        return $this->error;
    }

	function showError($msg) {
		$this->error[] = $msg;
		return true;
	}
}
?>